package com.terren.excavator.entity;

import java.util.HashMap;
import java.util.Map;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.document.Field.Store;

/**
 * 新增记录时类
 * @author Administrator
 *
 */
public class LuceneField {
	private String fieldName;//字段名称
	private String fieldValue;//字段值
	private String fieldType;//字段类型	StringField	IntField	TextField
	
	public String getFieldName() {
		return fieldName;
	}
	public void setFieldName(String fieldName) {
		this.fieldName = fieldName;
	}
	public String getFieldValue() {
		return fieldValue;
	}
	public void setFieldValue(String fieldValue) {
		this.fieldValue = fieldValue;
	}
	public String getFieldType() {
		return fieldType;
	}
	public void setFieldType(String fieldType) {
		this.fieldType = fieldType;
	}
	
	/**
	 * 根据当前 luceneField 生成一个 field 字段
	 * @return
	 */
	public Field getField(){
		Field field = null;
		try {
			if("StringField".equalsIgnoreCase(fieldType)){
				field = new StringField(fieldName, fieldValue, Store.YES);
			}else if("TextField".equalsIgnoreCase(fieldType)){
				field = new TextField(fieldName, fieldValue, Store.YES);
			}else if("IntField".equalsIgnoreCase(fieldType)){
				int value = Integer.parseInt(fieldValue);
				field = new IntField(fieldName, value, Store.YES);
			}else if("LongField".equalsIgnoreCase(fieldType)){
				long value = Long.parseLong(fieldValue);
				field = new LongField(fieldName, value, Store.YES);
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return field;
	}
	
	/**
	 * 通过 luceneField 生成 document
	 * @param fieldMap
	 * @return
	 */
	public static Document createDocument(Map<String, LuceneField> fieldMap){
		Document document = new Document();
		
		for(LuceneField luceneField : fieldMap.values()){
			Field field = luceneField.getField();
			
			if(field == null){
				return null;
			}
			document.add(field);
		}
		if(document.getFields().size() <= 0){
			document = null;
		}
		
		return document;
	}
	
	public static void main(String[] args) {
		Map<String, LuceneField> fieldMap = new HashMap<String, LuceneField>();
		Document doc = createDocument(fieldMap);
		int a = doc.getFields().size();
		
		System.out.println(a);
		
	}
}
